'''
Created on 29/03/2011

@author: Eran_Z

Scoring
'''

from search_m import searchSingle, searchTogether
from util_m import sum, BadMovie

#Helper functions:

def __normalizedSigmaMutualWeightHelper(w, ci, wi):
    ss = searchSingle(w)
    st = searchTogether(w, ci)
    #return 0 if ss < st else st*wi*1.0/ss
    if ss < st:
        raise BadMovie
    return st*wi*1.0/ss

def __normalizedSigmaMutualWeight(w, context, weights):
    try:
        return reduce(sum, map(lambda i:__normalizedSigmaMutualWeightHelper(w, context[i], weights[i]), range(len(context))))
    except BadMovie:
        return 0
    
########################################################
########################################################
#Main functions:

def normalizedMutualInformationScorer(context, weights, world):
    return map(lambda w:__normalizedSigmaMutualWeight(w, context, weights), world)




#------------- UNUSED EXTENSIONS --------------------
from search_m import searchExclusion, NGD


def __sigmaMutualWeight(w, context, weights):
    return reduce(sum, map(lambda i:searchTogether(w, context[i])*weights[i], range(len(context))))
    


def basicScorer(context, weights, world):
    #Note: uses searchExclusion, which is uncached...
    return map(lambda w:__sigmaMutualWeight(w, context, weights)*1.0/(searchSingle(w)-searchExclusion(w, context)), world)

def NGD1Scorer(context, weights, world):
    return 1.0/(reduce(sum, map(lambda i:NGD(world[i], context[i])*weights[i], range(len(context)))))

def NGD2Scorer(context, weights, world):
    return reduce(sum, map(lambda i:1.0/(NGD(world[i], context[i])*weights[i]), range(len(context))))

def regularMutualInformationScorer(context, weights, world):
    return map(lambda w:__sigmaMutualWeight(w, context, weights), world)

#-----------------------------------------

scoringAlgorithms = {"Basic": basicScorer, "NGD Type 1": NGD1Scorer, "NGD Type 2": NGD2Scorer,
                     "Regular Mutual Information": regularMutualInformationScorer,
                     "Normalized Mutual Information": normalizedMutualInformationScorer }
